package com.ruibang.glass.purchase.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceStatus;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.purchase.constant.Constants;
import com.ruibang.glass.purchase.constant.PurchaseErrorCode;
import com.ruibang.glass.purchase.domain.req.PurchaseReportReq;
import com.ruibang.glass.purchase.entity.PurchaseApprovalList;
import com.ruibang.glass.purchase.entity.PurchaseBidEvaluationReports;
import com.ruibang.glass.purchase.entity.ProcureReportBidders;
import com.ruibang.glass.purchase.feign.CamundaApi;
import com.ruibang.glass.purchase.feign.FileApi;
import com.ruibang.glass.purchase.mapper.PurchaseBidEvaluationReportsMapper;
import com.ruibang.glass.purchase.mapper.PurchaseApprovalListMapper;
import com.ruibang.glass.purchase.service.PurchaseBidEvaluationReportsService;
import com.ruibang.glass.purchase.service.ProcureReportBiddersService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 销售评标报告 服务实现类
 * </p>
 *
 * @author mameng
 * @since 2024-03-27
 */
@Service
public class PurchaseBidEvaluationReportsServiceImpl extends ServiceImpl<PurchaseBidEvaluationReportsMapper, PurchaseBidEvaluationReports> implements PurchaseBidEvaluationReportsService {

    @Autowired
    private ProcureReportBiddersService gProcureReportBiddersService;

    @Autowired
    private FileApi fileApi;
    @Autowired
    private RedisSingleService redisService;

    @Autowired
    private CamundaApi camundaApi;

    @Autowired
    private PurchaseApprovalListMapper approvalListMapper;
    private static final String PURCHASE_JSWD = "sale_contract_jswd_file";//技术资格文档
    private static final String PURCHASE_SWWJ = "sale_contract_swwj_file";//商务文件
    private static final String PURCHASE_FJ = "sale_contract_Fj_file";//附件
    /**
     * 分页
     * @param purchaseReportReq
     * @return
     */
    @Override
    public IPage<PurchaseBidEvaluationReports> getPage(PurchaseReportReq purchaseReportReq) {
        IPage<PurchaseBidEvaluationReports> page = baseMapper.getPage(new Page<>(purchaseReportReq.getPageNo(), purchaseReportReq.getPageSize()), purchaseReportReq);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return page;
        }
        Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
        List<String> businessKeys = page.getRecords().stream().map(PurchaseBidEvaluationReports::getId).collect(Collectors.toList());
        Map<String, BpmProcessInstanceStatus> processMap = null;
        //获取业务流程状态
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(businessKeys);
        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
            processMap = resultBody.getData().stream().collect(Collectors.toMap(bp->bp.getBusinessKey(), bp->bp, (bp1, bp2) -> bp1));
        }
        for (PurchaseBidEvaluationReports qualityContact : page.getRecords()) {
            if(processMap!=null && processMap.get(qualityContact.getId()) != null){
                BpmProcessInstanceStatus instance = processMap.get(qualityContact.getId());
                qualityContact.setStatus(String.valueOf(instance.getStatus()));
                qualityContact.setProcessId(instance.getProcessInstanceId());
                qualityContact.setApproveStatus(instance.getResult());
                qualityContact.setNodeName(instance.getNodeName());
                if (StringUtils.isNotBlank(instance.getUserId())) {
                    if(instance.getUserId().indexOf(CommonConstant.SpecialSign.COMMA.getName())!=-1){
                        String[] userIds= instance.getUserId().split(CommonConstant.SpecialSign.COMMA.getName());
                        StringBuilder userName = new StringBuilder();
                        int size = userIds.length;
                        for (int i=0;i< size;i++) {
                            String name = userMap.get(userIds[i])==null?"":userMap.get(userIds[i]).toString();
                            if(i==size-1){
                                userName.append(name);
                            }else{
                                userName.append(name).append(CommonConstant.SpecialSign.COMMA.getName());
                            }
                        }
                        qualityContact.setApproveUserId(instance.getUserId());
                        qualityContact.setApproveUserName(userName.toString());
                    }else{
                        qualityContact.setApproveUserId(instance.getUserId());
                        qualityContact.setApproveUserName(userMap.get(instance.getUserId())==null?"":userMap.get(instance.getUserId()).toString());
                    }
                }
            }

            Object evaluationTeamLeader = userMap.get(qualityContact.getEvaluationTeamLeader());
            if (evaluationTeamLeader!=null){
                qualityContact.setEvaluationTeamLeader(evaluationTeamLeader.toString());
            }
        }
        return page;
    }
    /**
     * 流程添加
     * @param report
     * @return
     */
    @Override
    public void addGProcureReportBidders(PurchaseBidEvaluationReports report) {
        long count = this.count(Wrappers.<PurchaseBidEvaluationReports>lambdaQuery().eq(PurchaseBidEvaluationReports::getProjectNumber,report.getProjectNumber()));
        if(count>0){
            throw new ServiceException(PurchaseErrorCode.PURCHASE_REPORT_IS_EXIST.getCode(),PurchaseErrorCode.PURCHASE_REPORT_IS_EXIST.getMsg());
        }
        if(StringUtils.isNotBlank(report.getProjectNumber())){
            String isUsed = approvalListMapper.getUsedByNumber(report.getProjectNumber());
            if(StringUtils.isBlank(isUsed)){
                throw new ServiceException(PurchaseErrorCode.PROJECT_NUMBER_IS_NOT_NULL.getCode(),PurchaseErrorCode.PROJECT_NUMBER_IS_NOT_NULL.getMsg());
            }else{
                if(CommonConstant.ONE_STR.equals(isUsed)){
                    throw new ServiceException(PurchaseErrorCode.SELECT_PROJECT_IS_USED.getCode(),PurchaseErrorCode.SELECT_PROJECT_IS_USED.getMsg());
                }else{
                    approvalListMapper.updateReportByNumber(report.getProjectNumber(), Constants.ONE_STR);
                }
            }
        }else{
            throw new ServiceException(PurchaseErrorCode.PROJECT_NUMBER_IS_NOT_NULL.getCode(),PurchaseErrorCode.PROJECT_NUMBER_IS_NOT_NULL.getMsg());
        }
        baseMapper.insert(report);
        if (CollectionUtils.isNotEmpty(report.getFileIdList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setBusinessId(report.getId());
            fileBusiness.setFileIds(report.getFileIdList());
            fileApi.updateBusinessById(fileBusiness);
        }
        //BigDecimal bigDecimal = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(report.getProcureReportBidders())) {
            List<ProcureReportBidders> procureReportBidders = report.getProcureReportBidders();
            for (ProcureReportBidders reportBidders : procureReportBidders) {
                if (CommonConstant.ONE_STR.equals(reportBidders.getIsWinningBid()) && reportBidders.getWinningBidAmount() == null) {
                    throw new ServiceException(PurchaseErrorCode.NO_AMOUNT.getCode(), PurchaseErrorCode.NO_AMOUNT.getMsg());
                }
                reportBidders.setId(null);
                reportBidders.setIsUsed(CommonConstant.ZERO_STR);
                reportBidders.setBidEvaluationReportId(report.getId());
                gProcureReportBiddersService.save(reportBidders);

                if (!CollectionUtils.isEmpty(reportBidders.getTechnicalQualificationDocumentIds())) {
                    FileBusiness fileBusiness = new FileBusiness();
                    fileBusiness.setBusinessId(reportBidders.getId());
                    fileBusiness.setFileIds(reportBidders.getTechnicalQualificationDocumentIds());
                    fileBusiness.setAttribute(PURCHASE_JSWD);
                    fileApi.updateBusinessById(fileBusiness);
                }
                if (!CollectionUtils.isEmpty(reportBidders.getCommercialDocumentIds())) {
                    FileBusiness fileBusiness = new FileBusiness();
                    fileBusiness.setBusinessId(reportBidders.getId());
                    fileBusiness.setFileIds(reportBidders.getCommercialDocumentIds());
                    fileBusiness.setAttribute(PURCHASE_SWWJ);
                    fileApi.updateBusinessById(fileBusiness);
                }
            }
        }
    }
    /**
     * 跟新
     * @param procureBidEvaluationReports
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGProcureBidEvaluationReports(PurchaseBidEvaluationReports procureBidEvaluationReports) {
        baseMapper.updateById(procureBidEvaluationReports);
        fileApi.deleteByBusinessId(procureBidEvaluationReports.getId());
        if (CollectionUtils.isNotEmpty(procureBidEvaluationReports.getFileIdList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setBusinessId(procureBidEvaluationReports.getId());
            fileBusiness.setFileIds(procureBidEvaluationReports.getFileIdList());
            fileApi.updateBusinessById(fileBusiness);
        }
        if (CollectionUtils.isNotEmpty(procureBidEvaluationReports.getProcureReportBidders())) {
            List<ProcureReportBidders> procureReportBidders = procureBidEvaluationReports.getProcureReportBidders();
            gProcureReportBiddersService.remove(Wrappers.<ProcureReportBidders>lambdaQuery().eq(ProcureReportBidders::getBidEvaluationReportId,procureBidEvaluationReports.getId()));
            for (ProcureReportBidders gPurchasePurchaseRequestItems : procureReportBidders) {
                gPurchasePurchaseRequestItems.setBidEvaluationReportId(procureBidEvaluationReports.getId());
                gProcureReportBiddersService.save(gPurchasePurchaseRequestItems);
                FileBusiness fileBusiness = new FileBusiness();
                fileBusiness.setBusinessId(gPurchasePurchaseRequestItems.getId());
                fileBusiness.setAttribute(PURCHASE_JSWD);
                fileApi.deleteByBusinessIdAndAttribute(fileBusiness);
                if (!CollectionUtils.isEmpty(gPurchasePurchaseRequestItems.getTechnicalQualificationDocumentIds())) {
                    fileBusiness.setFileIds(gPurchasePurchaseRequestItems.getTechnicalQualificationDocumentIds());
                    fileApi.updateBusinessById(fileBusiness);
                }

                fileBusiness.setAttribute(PURCHASE_SWWJ);
                fileApi.deleteByBusinessIdAndAttribute(fileBusiness);
                if (!CollectionUtils.isEmpty(gPurchasePurchaseRequestItems.getCommercialDocumentIds())) {
                    fileBusiness.setFileIds(gPurchasePurchaseRequestItems.getCommercialDocumentIds());
                    fileApi.updateBusinessById(fileBusiness);
                }
            }
        }

    }
    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public PurchaseBidEvaluationReports getDetail(String id) {
        PurchaseBidEvaluationReports gProcureBidEvaluationReports = baseMapper.selectById(id);
        ResultBody<List<String>> fileIdsByBusinessId = fileApi.getFileIdsByBusinessId(id);

        if (fileIdsByBusinessId!=null&&CollectionUtils.isNotEmpty(fileIdsByBusinessId.getData())) {
            gProcureBidEvaluationReports.setFileIdList(fileIdsByBusinessId.getData());
        }
        List<ProcureReportBidders> list = gProcureReportBiddersService.list(Wrappers.<ProcureReportBidders>lambdaQuery().eq(ProcureReportBidders::getBidEvaluationReportId, id));
        if(CollectionUtils.isNotEmpty(list)){
            List<String> ids = list.stream().map(ProcureReportBidders::getId).collect(Collectors.toList());
            ResultBody<List<FileBusiness>> fileBusinessesRs = fileApi.getFileBusinessByIds(ids);
            Map<String,FileBusiness> fileMap = null;
            if(fileBusinessesRs!=null&&CollectionUtils.isNotEmpty(fileBusinessesRs.getData())){
                fileMap = fileBusinessesRs.getData().stream().collect(Collectors.toMap(FileBusiness::getBusinessId,fb->fb,(fb1,fb2)->fb1));
            }



            for (ProcureReportBidders gProcureReportBidders : list) {
                if(fileMap!=null){
                    FileBusiness fileBusiness = fileMap.get(gProcureReportBidders.getId().concat(PURCHASE_JSWD));
                    if (fileBusiness != null) {
                        gProcureReportBidders.setTechnicalQualificationDocumentIds(fileBusiness.getFileIds());
                    }
                    fileBusiness = fileMap.get(gProcureReportBidders.getId().concat(PURCHASE_SWWJ));
                    if (fileBusiness != null) {
                        gProcureReportBidders.setCommercialDocumentIds(fileBusiness.getFileIds());
                    }
                }
            }

            gProcureBidEvaluationReports.setProcureReportBidders(list);
        }

        if(gProcureBidEvaluationReports!=null){
            Object userNameObj = redisService.hget(RedisKey.USER_GROUP_TYPE,gProcureBidEvaluationReports.getEvaluationTeamLeader());
            if(userNameObj!=null){
                gProcureBidEvaluationReports.setEvaluationTeamLeaderName(userNameObj.toString());
            }
        }

        return gProcureBidEvaluationReports;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeInfo(String id) {
        if (StringUtils.isNotBlank(id)){
            PurchaseBidEvaluationReports purchaseBidEvaluationReports = this.getById(id);
            if (purchaseBidEvaluationReports!=null){
                approvalListMapper.updateReportByNumber(purchaseBidEvaluationReports.getProjectNumber(),Constants.ZERO_STR);
            }
            this.removeById(id);
        }
    }

    @Override
    public List<PurchaseBidEvaluationReports> getContractsProject() {
        return baseMapper.getContractsProject(CommonConstant.ONE_STR);
    }

    @Override
    public List<PurchaseBidEvaluationReports> getFrameContractsProject() {
        List<PurchaseBidEvaluationReports> reportsList = new ArrayList<>();
        List<PurchaseApprovalList> approvalLists = approvalListMapper.getFrameContractsProject();
        if(CollectionUtils.isNotEmpty(approvalLists)){
            for (PurchaseApprovalList approvalList : approvalLists) {
                PurchaseBidEvaluationReports report = new PurchaseBidEvaluationReports();
                report.setId(approvalList.getId());
                report.setProjectName(approvalList.getProjectName());
                report.setProjectNumber(approvalList.getNumber());
                report.setPurchaseMethod(approvalList.getPurchaseMode());
                reportsList.add(report);
            }
        }

        List<PurchaseBidEvaluationReports> reports = baseMapper.getContractsProject(CommonConstant.THREE_STR);
        if(CollectionUtils.isNotEmpty(reports)){
            reportsList.addAll(reports);
        }

        return reportsList.stream().distinct().collect(Collectors.toList());
    }
}
